<script lang="ts" setup>
import type { WaybillCarrierOwnerBill } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getWaybillCarrierOwnerBillById } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import DetailCard from '@/components/DetailCard.vue'
import useFlow from '@/hooks/useFlow'
import useLoading from '@/hooks/useLoading'

// 页面配置
definePage({
  style: {
    navigationBarTitleText: '业务费用详情',
    backgroundColor: '#f5f5f5',
  },
  enablePullDownRefresh: true,
})

const { loading, startLoading, endLoading } = useLoading()
const expenseDetail = ref<WaybillCarrierOwnerBill | null>(null)
const flowIdValue = ref<string>('')
const idValue = ref<string>('')
const currentTab = ref<'detail' | 'attachment'>('detail')

// 使用流程hook
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId, loading: flowLoading } = useFlow()

// 获取审批状态显示文本
function getApprovalStatusText(status: number | undefined): string {
  const statusMap = {
    0: '待提交',
    1: '待审批',
    2: '审批中',
    3: '已通过',
    4: '已拒绝',
    5: '已撤销',
  }
  return statusMap[status as keyof typeof statusMap] || '未知状态'
}

// 获取资金类型显示文本
function getFundsTypeText(type: number | undefined): string {
  const typeMap = {
    1: '收入',
    2: '支出',
  }
  return typeMap[type as keyof typeof typeMap] || '未知类型'
}

// 获取结算类型显示文本
function getSettlementTypeText(type: number | undefined): string {
  const typeMap = {
    1: '应收',
    2: '应付',
  }
  return typeMap[type as keyof typeof typeMap] || '未知类型'
}

// 获取布尔值显示文本
function getBooleanText(value: number | undefined): string {
  return value === 1 ? '是' : '否'
}

// 获取支付类型显示文本
function getPayTypeText(type: number | null | undefined): string {
  if (type === null || type === undefined)
    return '-'
  const typeMap = {
    1: '现金',
    2: '银行转账',
    3: '支票',
    4: '其他',
  }
  return typeMap[type as keyof typeof typeMap] || '未知类型'
}

// 获取运单状态显示文本
function getWaybillStateText(state: number | undefined): string {
  const stateMap = {
    1: '待确认',
    2: '已确认',
    3: '在途',
    4: '已签收',
    5: '已取消',
    6: '已完成',
  }
  return stateMap[state as keyof typeof stateMap] || '未知状态'
}

// 获取是否支付显示文本
function getIsPayText(value: number | undefined): string {
  const payMap = {
    0: '未支付',
    1: '部分支付',
    2: '已支付',
  }
  return payMap[value as keyof typeof payMap] || '未知状态'
}

// 获取是否已登记显示文本
function getIsRegisteredText(value: number | undefined): string {
  const registeredMap = {
    1: '已登记',
    2: '未登记',
  }
  return registeredMap[value as keyof typeof registeredMap] || '未知状态'
}

// 基本信息卡片数据
const basicInfo = computed<InfoItem[]>(() => {
  if (!expenseDetail.value)
    return []
  return [
    { label: '业务编号', value: expenseDetail.value.businessNo || '-' },
    { label: '费用类型', value: expenseDetail.value.costName || '-' },
    { label: '资金类型', value: getFundsTypeText(expenseDetail.value.fundsType) },
    { label: '结算类型', value: getSettlementTypeText(expenseDetail.value.settlementType) },
    { label: '业务时间', value: expenseDetail.value.businessTime || '-', type: 'datetime' },
    { label: '审批状态', value: getApprovalStatusText(expenseDetail.value.approvalStatus) },
    { label: '运单号', value: expenseDetail.value.waybillNo || '-' },
    { label: '运单状态', value: getWaybillStateText(expenseDetail.value.waybillState) },
  ]
})

// 收支信息卡片数据
const paymentInfo = computed<InfoItem[]>(() => {
  if (!expenseDetail.value)
    return []
  return [
    { label: '支付金额', value: expenseDetail.value.payment, type: 'currency' },
    { label: '收款金额', value: expenseDetail.value.receive, type: 'currency' },
    { label: '发票状态', value: getBooleanText(expenseDetail.value.isInvoice) },
    { label: '发票金额', value: expenseDetail.value.invoiceAmount, type: 'currency' },
    { label: '是否退款', value: getBooleanText(expenseDetail.value.isRefund) },
    { label: '支付类型', value: getPayTypeText(expenseDetail.value.payType) },
    { label: '是否已支付', value: getIsPayText(expenseDetail.value.isPay) },
  ]
})

// 业务信息卡片数据
const businessInfo = computed<InfoItem[]>(() => {
  if (!expenseDetail.value)
    return []
  return [
    { label: '业务机构', value: expenseDetail.value.businessInstitutionName || '-' },
    { label: '业务部门', value: expenseDetail.value.businessDepartmentName || '-' },
    { label: '业务员', value: expenseDetail.value.salesmanName || '-' },
    { label: '制单人', value: expenseDetail.value.createName || '-' },
    { label: '创建时间', value: expenseDetail.value.createTime || '-', type: 'datetime' },
    { label: '更新人', value: expenseDetail.value.updateName || '-' },
    { label: '更新时间', value: expenseDetail.value.updateTime || '-', type: 'datetime' },
  ]
})

// 结算信息卡片数据
const settlementInfo = computed<InfoItem[]>(() => {
  if (!expenseDetail.value)
    return []
  return [
    { label: '客户结算主体', value: expenseDetail.value.customerSettlementEntityName || '-' },
    { label: '系统结算主体', value: expenseDetail.value.systemSettlementEntityName || '-' },
    { label: '是否已登记', value: getIsRegisteredText(expenseDetail.value.isRegistered) },
    { label: '冻结状态', value: getBooleanText(expenseDetail.value.freezeStatus) },
    { label: '冻结时间', value: expenseDetail.value.freezeTime || '-', type: 'datetime' },
    { label: '解冻时间', value: expenseDetail.value.unfreezeTime || '-', type: 'datetime' },
  ]
})

// 流程信息卡片数据
const processInfo = computed<InfoItem[]>(() => {
  if (!currentProcess.value)
    return []
  return [
    { label: '流程实例ID', value: currentProcess.value.id || '-' },
    { label: '当前活动', value: currentProcess.value.category || '-' },
    { label: '流程状态', value: currentProcess.value.status || '-' },
  ]
})

// 其他信息卡片数据
const otherInfo = computed<InfoItem[]>(() => {
  if (!expenseDetail.value)
    return []
  return [
    { label: '业务描述', value: expenseDetail.value.description || '-', forceMultiline: true },
    { label: '支付方', value: expenseDetail.value.payerName || '-' },
  ]
})

// 数据获取函数
async function loadData(id: string) {
  try {
    startLoading()
    await getProcessInstance(id)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    if (currentProcess.value) {
      const res = await getWaybillCarrierOwnerBillById(currentProcess.value.businessKey)
      expenseDetail.value = res.data || null
    }
  }
  catch (error) {
    console.error('获取业务费用详情失败:', error)
  }
  finally {
    endLoading()
  }
}

// 页面加载时获取数据
onLoad((e) => {
  const { id, flowId } = e
  if (flowId) {
    flowIdValue.value = flowId as string
  }
  if (id) {
    idValue.value = id as string
    loadData(id as string)
  }
})
</script>

<template>
  <view class="page">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <view v-if="loading || flowLoading" class="loading-container">
      <view class="loading">
        加载中...
      </view>
    </view>

    <view v-else-if="expenseDetail" class="detail-content">
      <!-- Tab导航栏 -->
      <view class="tab-nav">
        <view
          class="tab-item"
          :class="{ 'tab-active': currentTab === 'detail' }"
          @click="currentTab = 'detail'"
        >
          费用详情
        </view>
        <view
          class="tab-item"
          :class="{ 'tab-active': currentTab === 'attachment' }"
          @click="currentTab = 'attachment'"
        >
          结算信息
        </view>
      </view>

      <!-- 费用详情Tab -->
      <view v-show="currentTab === 'detail'" class="tab-content">
        <!-- 基础信息卡片 -->
        <DetailCard title="基础信息" :info-list="basicInfo" :show-divider="true" />

        <!-- 收支信息卡片 -->
        <DetailCard title="收支信息" :info-list="paymentInfo" :show-divider="true" />

        <!-- 业务信息卡片 -->
        <DetailCard title="业务信息" :info-list="businessInfo" :show-divider="true" />

        <!-- 其他信息卡片 -->
        <DetailCard title="其他信息" :info-list="otherInfo" :show-divider="true" />

        <!-- 流程信息卡片 -->
        <DetailCard title="流程信息" :info-list="processInfo" :show-divider="true" />
      </view>

      <!-- 结算信息Tab -->
      <view v-show="currentTab === 'attachment'" class="tab-content">
        <!-- 结算信息卡片 -->
        <DetailCard title="结算信息" :info-list="settlementInfo" :show-divider="true" />
      </view>

      <!-- 审批操作按钮区域 -->
      <ApprovalActionBar v-if="flowIdValue && currentProcess?.status === 1" :process-id="flowIdValue" />
    </view>

    <view v-else class="error-container">
      <view class="error-message">
        暂无数据
      </view>
    </view>
  </view>
</template>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 50vh;
  color: #999;
}

.detail-content {
  padding: 20rpx;

  .tab-nav {
    display: flex;
    width: 100%;
    background-color: #fff;
    border-radius: 12rpx 12rpx 0 0;
    margin-bottom: 0;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */

    &::-webkit-scrollbar {
      display: none; /* Chrome, Safari and Opera */
    }
  }

  .tab-item {
    min-width: 200rpx;
    text-align: center;
    padding: 30rpx 40rpx;
    font-size: 28rpx;
    color: #666;
    border-bottom: 4rpx solid transparent;
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
  }

  .tab-item:last-child {
    margin-right: 20rpx;
  }

  .tab-item:first-child {
    margin-left: 20rpx;
  }

  .tab-active {
    color: #1890ff;
    font-weight: 600;
    background-color: #f8f9fa;

    &::after {
      content: '';
      position: absolute;
      bottom: -2rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 6rpx;
      background-color: #1890ff;
      border-radius: 3rpx;
    }
  }

  .tab-content {
    background-color: #fff;
    border-radius: 0 0 12rpx 12rpx;
    margin-bottom: 20rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }

  .empty-message {
    text-align: center;
    padding: 80rpx 20rpx;
    color: #999;
    font-size: 26rpx;
  }
}
</style>
